package com.mrobuy.util;

import com.google.common.io.Files;
import okhttp3.*;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;


public class HttpUtils {

	public final  static List<Cookie> cache = new ArrayList<>();

    private static final OkHttpClient client = new OkHttpClient.Builder()
													.connectTimeout(15, TimeUnit.SECONDS)
													.readTimeout(15, TimeUnit.MINUTES)
													.cookieJar(new CookieJar() {
														@Override
														public void saveFromResponse(HttpUrl httpUrl, List<Cookie> list) {
															//内存中缓存Cookie
															cache.addAll(list);
														}

														@Override
														public List<Cookie> loadForRequest(HttpUrl url) {
															//过期的Cookie
															List<Cookie> invalidCookies = new ArrayList<>();
															//有效的Cookie
															List<Cookie> validCookies = new ArrayList<>();

															for (Cookie cookie : cache) {

																if (cookie.expiresAt() < System.currentTimeMillis()) {
																	//判断是否过期
																	invalidCookies.add(cookie);
																} else if (cookie.matches(url)) {
																	//匹配Cookie对应url
																	validCookies.add(cookie);
																}
															}

															//缓存中移除过期的Cookie
															cache.removeAll(invalidCookies);

															//返回List<Cookie>让Request进行设置
															return validCookies;
														}
													})
    												.build();

    public static final String USERAGENT = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, lko) Chrome/81.0.4044.129 Safari/537.36";


	public static void download(String url, String localFilePath) throws IOException {

		File dir = new File(localFilePath);
		if (dir.getParentFile()!=null && !dir.getParentFile().exists() ) {
			dir.getParentFile().mkdirs();
		}

		//2.创建Request对象
		Request request  = new Request.Builder()
				.url(url)
				.header("User-Agent", USERAGENT)
				.build();

		//3.异步请求newCall（Callback）
		Call call = client.newCall(request);

		Response response = call.execute();
		try {
			if ( response.isSuccessful() ) {
				Files.write(response.body().bytes(), new File(localFilePath));
			} else {
				throw new RuntimeException("[" + response.code() + "]" + response.message()) ;
			}
		} finally {
			response.close();
		}

	}

}
